<?php
require_once(dirname(__FILE__).'/../config.php');
//处理方面
if($_POST)
{
	global $dsql;
	$enews = $_POST['enews'];
	//处理微信扫码登录二维码请求写入
	if($enews=="wxlogin")
	{
		$etime = $_POST['time'];
		if(!$etime)
		{
		  echo "dberror";exit;
		}
		
		$query = "INSERT INTO `#@__wxlogin_ewm`(time) values('$etime')";

		if($dsql->ExecuteNoneQuery($query))
		{
			echo "success";exit;
		}
		else
		{
			echo "dberror";exit;
		}
	}
	//处理微信扫码授权写入openid参数
	if($enews=="wxsq")
	{
		$etime		=	$_POST['etime'];
		$openid		=	$_POST['openid'];
		$username	=	$_POST['username'];
		$userpic	=	$_POST['userpic'];
		$address	=	$_POST['address'];
		$gzzt		=	$_POST['gzzt'];
		if(!$etime)
		{
			echo "dberror";exit;
		}
		//判断二维码是否过期
		$daytime = time();
		$endtime = $daytime-$etime;
		if($endtime >= 600)
		{
			echo "endtime";exit;
		}
		//判断二维码是否已登录
		$sq = $dsql->GetOne("select * from `#@__wxlogin_ewm` where time='$etime'");
		if($sq['openid'])
		{
			echo "islogin";exit;
		}
		//删除过期二维码
		$sctime = $daytime-600;
		$dsql->ExecuteNoneQuery(" delete from `#@__wxlogin_ewm` where time<'$sctime' ");

		//写入授权参数
		$rs = $dsql->ExecuteNoneQuery2("update `#@__wxlogin_ewm` set openid='$openid',username='$username',userpic='$userpic',address='$address',gzzt='$gzzt' where time='$etime' ");
		
		if($rs <= 0)
		{
		   echo "dberror";exit; 
		}
		else
		{
		   echo "success";exit;
		} 
	}

    //处理监听扫码后参数获取
	if($enews=="login")
	{
		
		$tzde = trim($_REQUEST['tz']);		
		if(!empty($tzde)){
			$back_actz =  urldecode($tzde);
		}else{
		    $back_actz = '/index.php';
		}		
		$etime = $_POST['etime'];
		$sq = $dsql->GetOne("select * from `#@__wxlogin_ewm` where time='$etime'");
		if($sq['openid'])
		{
			$openid		=	$sq['openid'];
			$logincook	=	315360000;
			$userpic	=	$face = str_replace('http:', '', $sq['userpic']);//头像
			$username	=	$nickname = $sq['username'];//昵称
			$address	=	$sq['address'];;//用户地区
			$wxfollow	=	$sq['gzzt'];
			$sex = '男';
			$mtype = '个人';
			$dfscores = 0;
			$dfmoney = 0;
			$dfrank = $dsql->GetOne("SELECT money,scores FROM `#@__arcrank` WHERE rank='10' ");
			if (is_array($dfrank)) {
			$dfmoney = $dfrank['money'];
			$dfscores = $dfrank['scores'];
			}
			$jointime = $logintime = time();
			$joinip =  $loginip = GetIP();
			$spaceSta = 0;
			$_SESSION['jj_openid'] = $openid;
			$_SESSION['jj_nickname'] = $nickname;
			$_SESSION['jj_face'] = $face;
			$_SESSION['jj_sex'] = $sex;
			if(!$wxfollow)
			{
			$wxfollow=0;
			}
			$uarr = $dsql->GetOne("select * from #@__member where `jjwxopenid` = '$openid'");
			if (is_array($uarr)) { //存在即登陆
				$cfg_ml->PutLoginInfo($uarr['mid']);
				$cfg_ml->DelCache($uarr['mid']);
				echo "success";exit;
			} else { //不存在 看用户是否已登录
				//如果已经登录了
				if (!empty($cfg_ml->M_ID)) {
				  //绑定微信 
				  $sql = "update #@__member set `jjwxopenid` = '" . $_SESSION['jj_openid'] . "',`uname` = '" . $_SESSION['jj_nickname'] . "',`face` = '" . $_SESSION['jj_face'] . "',`sex` = '" . $_SESSION['jj_sex'] . "' where mid = '" . $cfg_ml->M_ID . "' ";
				  $dsql->ExecuteNoneQuery($sql);
				  $_SESSION['jj_openid'] = '';
				  $_SESSION['jj_nickname'] = '';
				  $_SESSION['jj_face'] = '';
				  $_SESSION['jj_sex'] = '';
				  ShowMsg("微信绑定成功...", $back_actz, 0, 1000);
				  exit;
				} else { //注册新用户
				  $userid = 'wx' . rand(10000000, 99999999);
		          $pp = "pwd";
                  if (function_exists('password_hash')) {
                  $pp = "pwd_new";
                  $pwd = password_hash($userpwd, PASSWORD_BCRYPT);
                  } else {
                  $pwd = md5('123456');
                  }
				  //推荐人
				  $tjrmid = GetCookie('tjrmid');
				  if (empty($tjrmid)) {
					$tjrmid = 0;
				  }
				  $inQuery = "INSERT INTO `#@__member` (`mtype` ,`userid` ,`uname`,`$pp` ,`sex` ,`rank` ,`money` ,`scores` , `matt`,
					`spacesta` ,`face`,`safequestion`,`safeanswer` ,`jointime` ,`joinip` ,`logintime` ,`loginip`,`jjwxopenid`,`tjrmid` )    
				  VALUES ('$mtype','$userid','微信用户','$pwd','$sex','10','$dfmoney','$dfscores',     
					 '0','$spaceSta','/static/web/img/avatar.png','$safequestion','$safeanswer','$jointime','$joinip','$logintime','$loginip','$openid','$tjrmid'); ";
				  $dsql->ExecuteNoneQuery($inQuery);
				  $mid = $dsql->GetLastID();
				  $space = 'person';
				  $membertjquery = "INSERT INTO `#@__member_tj` (`mid`,`article`,`album`,`archives`,`homecount`,`pagecount`,`feedback`,`friend`,`stow`)
							   VALUES ('$mid','0','0','0','0','0','0','0','0'); ";
				  $dsql->ExecuteNoneQuery($membertjquery);
				  $spacequery = "INSERT INTO `#@__member_space`(`mid` ,`pagesize` ,`matt` ,`spacename` ,`spacelogo` ,`spacestyle`, `sign` ,`spacenews`)
							VALUES('{$mid}','10','0','{$uname}的空间','','$space','',''); ";
				  $dsql->ExecuteNoneQuery($spacequery);
				  $dsql->ExecuteNoneQuery("INSERT INTO `#@__member_flink`(mid,title,url) VALUES('$mid','果泽森','https://www.guozesen.cn'); ");

                  /*
				  require_once DEDEINC . '/membermodel.cls.php';
				  $membermodel = new membermodel($mtype);
				  $modid = $membermodel->modid;
				  $modid = empty($modid) ? 0 : intval(preg_replace("/[^\d]/", '', $modid));
				  $modelform = $dsql->getOne("SELECT * FROM #@__member_model WHERE id='$modid' ");
				  $dsql->ExecuteNoneQuery("INSERT INTO `{$membermodel->table}` (`mid`) VALUES ('{$mid}');");
                  */

				  $cfg_ml->PutLoginInfo($mid);
				  $cfg_ml->DelCache($mid);
				  echo "success";exit;
				}
			}
		}
		else
		{
			echo "end";exit;
		}
	}

	//判断微信登陆
    if($enews=="islogin")
	{
        $u = isloginajax();
        $userid=$u['userid'];
        if($userid)
		{
            echo "success";exit;    
        }
		else
		{
            echo "dberror";exit;
        }
    }
}

function isloginajax()
{
	global $dsql,$cfg_ml;
	$userid  = $cfg_ml->M_LoginID;
	if(!$userid)
	{
		if( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false )
		{
			echo "wxnologin";exit;
		}
		else
		{
			echo "nologin";exit;
		} 
	}
	else
	{
		$add = $dsql->GetOne("select userid from `#@__member` where userid='$userid'");
		$u['userid'] = $userid;
	}
	$u['zt'] = $zt;
	return $userid;
}
?>